package com.sunfeng.jksj.p16;

import com.sunfeng.TimeUtils;

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Author : 孙峰
 * @Description:
 * @Date : 2022/1/21  14:29
 */
public class Test01 {
    static int count = 0;
    static Semaphore semaphore = new Semaphore(10, true);

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        ArrayList<Runnable> runnables = new ArrayList<>();

        for (int i = 0; i < 11; i++) {
            runnables.add(()->{
                try {
                    addOne();
                    TimeUtils.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        runnables.forEach(executorService::submit);


        System.out.println(count);

        executorService.shutdown();

    }

    public static void addOne() throws InterruptedException {
        semaphore.acquire();
        try {
            count += 1;
        } finally {
            semaphore.release();
        }
    }
}
